package com.ruoyi.web.controller.module.survey;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.RegexUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.survey.Survey;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.web.controller.common.BaseController;
import com.vdurmont.emoji.EmojiParser;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.module.survey.ISurveyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 问卷调查Controller
 *
 * @author ruoyi
 * @date 2021-09-05
 */
@Validated
@Api(value = "问卷调查控制器", tags = {"问卷调查管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/survey")
public class SurveyController extends BaseController {

    private final ISurveyService surveyService;
    private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final IWxUserService wxUserService;



	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询问卷调查列表
     */
    @ApiOperation("查询问卷调查列表")
    @PreAuthorize("@ss.hasPermi('module:survey:list')")
    @GetMapping("/list")
    public TableDataInfo<Survey> list(@Validated Survey survey) {
        SysUser sysUser = getUser();

        QueryWrapper<Survey> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(survey.getPropertyId() != null){
				qw.eq("property_id",survey.getPropertyId());
			}
		}

		if(survey.getSurveyType()!=null){
			qw.eq("survey_type",survey.getSurveyType());
		}
		if(survey.getFunctionType()!=null){
			qw.eq("function_type",survey.getFunctionType());
		}

		qw.orderByDesc("id");
        TableDataInfo<Survey> td = PageUtils.buildDataInfo(surveyService.page(PageUtils.buildPage(),qw));
		List<Survey> list = td.getRows();
		for (Survey survey1 : list){
			if(StrUtil.isNotEmpty(survey1.getQrCode())){
				survey1.setQrCode(imgUrl + survey1.getQrCode());
			}
		}
        return td;
    }

    /**
     * 导出问卷调查列表
     */
    @ApiOperation("导出问卷调查列表")
    @PreAuthorize("@ss.hasPermi('module:survey:export')")
    @Log(title = "问卷调查", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<Survey> export(@Validated Survey survey) {
        List<Survey> list = surveyService.list();
        ExcelUtil<Survey> util = new ExcelUtil<Survey>(Survey.class);
        return util.exportExcel(list, "问卷调查");
    }

    /**
     * 获取问卷调查详细信息
     */
    @ApiOperation("获取问卷调查详细信息")
    @PreAuthorize("@ss.hasPermi('module:survey:query')")
    @GetMapping("/{id}")
    public AjaxResult<Survey> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Survey survey = surveyService.getById(id);
        if(survey != null){
			WxUser wxUser = wxUserService.findById(survey.getFromWxUserId());
			if(wxUser!=null){
				if(StrUtil.isNotEmpty(wxUser.getNickName())){
					survey.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
				}
			}
		}
        return AjaxResult.success(survey);
    }

    /**
     * 新增问卷调查
     */
    @ApiOperation("新增问卷调查")
    @PreAuthorize("@ss.hasPermi('module:survey:add')")
    @Log(title = "问卷调查", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody Survey survey) {
    	if(survey.getPropertyId()!=null){
    		Property property = propertyService.findById(survey.getPropertyId());
    		if(property!=null){
				survey.setPropertyName(property.getPropertyName());
			}
		}
		if(survey.getEstateId()!=null){
			Estate estate = estateService.findById(survey.getEstateId());
			if(estate!=null){
				survey.setEstateName(estate.getEstateName());
			}
		}

		if(StrUtil.isNotEmpty(survey.getSurveyInfo())){
			String content = EmojiParser.parseToAliases(survey.getSurveyInfo());
			survey.setSurveyInfo(RegexUtil.convertProductDescription(content));
		}

		boolean bl = surveyService.save(survey);
		if(bl){
			try{
				String fileName = "survey_qr_" + survey.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/survey/info?id=" + survey.getId();
				int upload_type = FileUploadUtils.TYPE_SURVEY_QR_CODE;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, "NO. " + survey.getId() +" 问卷" , null, uploadPath +"/"+img_key, true, fileName, upload_type);
				survey.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			bl = surveyService.updateById(survey);
		}
        return toAjax(bl ? 1 : 0);
    }

    /**
     * 修改问卷调查
     */
    @ApiOperation("修改问卷调查")
    @PreAuthorize("@ss.hasPermi('module:survey:edit')")
    @Log(title = "问卷调查", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody Survey survey) {

		if(survey.getPropertyId()!=null){
			Property property = propertyService.findById(survey.getPropertyId());
			if(property!=null){
				survey.setPropertyName(property.getPropertyName());
			}
		}
		if(survey.getEstateId()!=null){
			Estate estate = estateService.findById(survey.getEstateId());
			if(estate!=null){
				survey.setEstateName(estate.getEstateName());
			}
		}
		if(StrUtil.isNotEmpty(survey.getSurveyInfo())){
			String content = EmojiParser.parseToAliases(survey.getSurveyInfo());
			survey.setSurveyInfo(RegexUtil.convertProductDescription(content));
		}
        return toAjax(surveyService.updateById(survey) ? 1 : 0);
    }



	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:survey:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody Survey survey) {
		if(survey.getId()!=null){
			try{
				survey = surveyService.getById(survey.getId());

				String fileName = "survey_qr_" + survey.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/survey/info?id=" + survey.getId();
				int upload_type = FileUploadUtils.TYPE_SURVEY_QR_CODE;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;

				QRCodeUtilEx.createQrCodeImg(content,survey.getQuestionTitle(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
				survey.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (surveyService.updateById(survey)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}


	/**
     * 删除问卷调查
     */
    @ApiOperation("删除问卷调查")
    @PreAuthorize("@ss.hasPermi('module:survey:remove')")
    @Log(title = "问卷调查" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(surveyService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
